package util.bitmap;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.widget.ImageView;

public class ImgView extends ImageView{

	public ImgView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		setScaleType(ScaleType.CENTER_CROP);
	}

	public ImgView(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
	}

	public ImgView(Context context) {
		this(context, null, 0);
	}
	
	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		if(0==radio){
			super.onMeasure(widthMeasureSpec, heightMeasureSpec);
		}else{
			int width = MeasureSpec.getSize(widthMeasureSpec);
			int height = MeasureSpec.getSize(heightMeasureSpec);
			switch(type){
			case TYPE_FIXED_WIDTH_WITH_SCALED_HEIGHT:
			case TYPE_FIXED_RADIO_AND_BASE_ON_WIDTH:
				height = (int) (width*radio);
				break;
			case TYPE_FIXED_HEIGHT_WITH_SCALED_WIDTH:
			case TYPE_FIXED_RADIO_AND_BASE_ON_HEIGHT:
				width = (int) (height*radio);
				break;
			}
			setMeasuredDimension(width, height);
		}
	}
	
	@Override
	protected void onDraw(Canvas canvas) {
		try {
			super.onDraw(canvas);
		} catch (Exception e) {
			e.printStackTrace();
		} catch(Error e){
			e.printStackTrace();
		}
	}
	
	@Override
	public void setImageBitmap(Bitmap bm) {
		if(null!=bm){
			if(type==TYPE_FIXED_HEIGHT_WITH_SCALED_WIDTH ){
					float newRadio = bm.getWidth()/(float)bm.getHeight();
					if(newRadio!=radio){
						radio = newRadio;
					}
			}else if(type==TYPE_FIXED_WIDTH_WITH_SCALED_HEIGHT){
					float newRadio = bm.getHeight()/(float)bm.getWidth();
					if(newRadio!=radio){
						radio = newRadio;
					}
			}
		}
		
		super.setImageBitmap(bm);
	}
	
	/**
	 * 设置高宽比（高/宽）,注意100/200=0, 100f/200=0.5f
	 */
	public void setRatioBaseOnWidth(float radio){
		if(this.radio!=radio){
			forceLayout();
			this.radio = radio;
		}
		type = TYPE_FIXED_RADIO_AND_BASE_ON_WIDTH;
	}
	
	public void setRadioBaseOnHeight(float radio){
		if(this.radio!=radio){
			forceLayout();
			this.radio = radio;
		}
		type = TYPE_FIXED_RADIO_AND_BASE_ON_HEIGHT;
	}

	public void setLayoutType(int type){
		this.type = type;
	}
	
	
	
	/**
	 * 宽度由LayoutParams确定
	 * 高度根据图片的宽高比和控件的宽度共同确定
	 */
	final public static int TYPE_FIXED_WIDTH_WITH_SCALED_HEIGHT  = 1;
	/**
	 * 高度由LayoutParams确定
	 * 宽度根据图片的宽高比和控件的高度共同确定
	 */
	final public static int TYPE_FIXED_HEIGHT_WITH_SCALED_WIDTH = 2;
	/**
	 * 宽度由LayoutParams确定
	 * 高度根据设定的宽高比和控件的宽度共同确定
	 */
	final public static int TYPE_FIXED_RADIO_AND_BASE_ON_WIDTH = 3;
	/**
	 * 高度由LayoutParams确定
	 * 宽度根据设定的宽高比和控件的高度共同确定
	 */
	final public static int TYPE_FIXED_RADIO_AND_BASE_ON_HEIGHT = 4;
	
	private int type = TYPE_FIXED_WIDTH_WITH_SCALED_HEIGHT; 
	
	private float radio = 0;
}
